package com.jelly.web.modules.system.quartz.service.impl;

import com.jelly.common.util.StringUtils;
import com.jelly.config.shiro.token.TokenUtil;
import com.jelly.web.modules.system.quartz.dao.QuartzMapper;
import com.jelly.web.modules.system.quartz.domain.Quartz;
import com.jelly.web.modules.system.quartz.domain.QuartzExample;
import com.jelly.web.modules.system.quartz.service.IQuartzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @创建人 ql
 * @创建时间 2018-09-26 14:36
 * @项目名称 jelly
 * @功能描述: 定时任务接口实现类
 **/
@Service
public class QuartzService implements IQuartzService {

    @Autowired
    private QuartzMapper quartzMapper;

    /**
     * 获取所有的定时任务
     * @return
     */
    @Override
    public List<Quartz> getQuartzAll() {
        return quartzMapper.selectByExample(new QuartzExample());
    }
    /**
     * 获取所有的定时任务
     * @return
     */
    @Override
    public List<Quartz> getQuartzAll(Quartz quartz) {
        QuartzExample example = new QuartzExample();
        QuartzExample.Criteria criteria = example.createCriteria();

        if(StringUtils.isNotBlank(quartz.getName())){

            criteria.andNameEqualTo(quartz.getName());

        }

        if(StringUtils.isNotBlank(quartz.getJobName())){

            criteria.andJobNameEqualTo(quartz.getJobName());

        }

        if(StringUtils.isNotBlank(quartz.getIsState())){

            criteria.andIsStateEqualTo(quartz.getIsState());

        }

        return quartzMapper.selectByExample(example);

    }

    /**
     * 主键修改定时任务
     * @param quartz
     * @return
     */
    @Override
    public Quartz updatQuartz(Quartz quartz) {
        if(StringUtils.isNotBlank(quartz.getBaseId())){
            quartz.setId(quartz.getBaseId());
        }
        quartz.setUpdateDate(new Date());
        quartz.setUpdateId(TokenUtil.getUserId());
        if(quartzMapper.updateByPrimaryKeySelective(quartz) > 0){
            return quartzMapper.selectByPrimaryKey(quartz.getId());
        }
        return null;
    }
    /**
     * 主键获取定时任务
     * @param id
     * @return
     */
    @Override
    public Quartz getQuartz(String id) {
        return quartzMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增定时任务
     * @param quartz
     * @return
     */
    @Override
    public boolean addQuartz(Quartz quartz) {
        quartz.setAddDate(new Date());
        quartz.setAddId(TokenUtil.getUserId());
        quartz.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        return quartzMapper.insertSelective(quartz) > 0;
    }

    /**
     * 删除定时任务
     * @param id
     * @return
     */
    @Override
    public boolean delectQuartz(String id) {
        return quartzMapper.deleteByPrimaryKey(id)>0;
    }
}
